package com.review.Demo_5_锁的其他概念;
/**
 * synchronized的重入：父子类之间的同步方法调用也是可以的
 * @author alienware
 *
 */
public class Sync_2_锁重入_2 {
	static class Main {
		public int i = 10;
		//public  void operationSup(){ //线程安全的
		public synchronized void operationSup(){  //线程安全的
			try {
				i--;
				System.out.println(Thread.currentThread().getName()+"Main print i = " + i);
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	static class Sub extends Main {
		public synchronized void operationSub(){//父子类的两个同步方法其实用的一个锁对象，所以线程是安全的
			try {
				while(i > 0) {
					i--;
					System.out.println(Thread.currentThread().getName()+"Sub print i = " + i);
					Thread.sleep(1000);		
					this.operationSup();
					Thread.sleep(3000);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		final Sub sub = new Sub();

		Thread t1 = new Thread(new Runnable() {
			public void run() {
				//Sub sub = new Sub();
				sub.operationSub();
			}
		});

		Thread t2 = new Thread(new Runnable() {
			public void run() {
				//Sub sub = new Sub();
				sub.operationSub();
			}
		});

		t1.start();
		t2.start();
	}

}
